const axios = require("axios");
let testDataString = "";
const getReaderText = (str) => {
  let matchStr = "";
  try {
    let resultList = str.match(/data:\s*({.*?})\s*\n/g);
    resultList &&
      resultList.forEach((_) => {
        const matchStrItem = _.match(/data:\s*({.*?})\s*\n/)[1];
        const data = JSON.parse(matchStrItem);
        matchStr += data?.choices[0].delta?.content || "";
      });
  } catch (e) {
    console.log(e);
  }
  return matchStr;
};
const url = "http://10.169.112.194:7100/v1/chat/completions";
const data = {
  model: "chatglm2-6b",
  messages: [
    {
      role: "user",
      content: "请实现一个登陆功能",
    },
  ],
  temperature: 0.75,
  stream: true,
};
const encode = new TextDecoder("utf-8");
axios
  .post(url, data, {
    responseType: "stream",
    headers: { "Content-Type": "application/json" },
  })
  .then((response) => {
    response.data.on("data", (value) => {
      const currentString = getReaderText(encode.decode(value));
      testDataString += currentString;
      console.log(currentString);
    });
    response.data.on("end", () => {
      console.log(testDataString);
    });
  });
